﻿using HDSmartCommunity.BUS;
using HDSmartCommunity.BUS.MqttBUS;
using HDSmartCommunity.DAL;
using HDSmartCommunity.DevicePlatform;
using HDSmartCommunity.HDPlatform;
using HDSmartCommunity.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net.NetworkInformation;
using System.Text;

namespace HDSmartCommunity.Serial
{
    public class SerialServer
    {
        public static DeviceSerialData serial = new DeviceSerialData();
        public static HDZHDeviceSerialData hdzh_serial = new HDZHDeviceSerialData();
        public static SHGDDeviceSerialData shgd_serial = new SHGDDeviceSerialData();
        public static PZDeviceSerialData pz_serial = new PZDeviceSerialData();
        public static DYDeviceSerialData dy_serial = new DYDeviceSerialData();
        public static DataSaveDeviceSerialData data_serial = new DataSaveDeviceSerialData();
        public static CEMSDeviceSerialData cems_serial = new CEMSDeviceSerialData();
        public DevInfo dev;
        public static HDProcessData devState = new HDProcessData();
        public static HDZHProcessData hdzh_devState = new HDZHProcessData();
        public static RaspberryPie raspberryPie = new RaspberryPie();
        public LogPrint log = new LogPrint();
        public static FXMqttClient FXMqttClient;
        public static string publickey;
        public static int Encry;
        public static PZMqttClient PZMqttClient;

        public SerialServer()
        {
            JsonConfigHelper jsonConfigHelper = new JsonConfigHelper("appsettings.json");

            dev = serial.GetDevInfo();


            if (dev.authmode == 1)
            {
                List<FloorInfo> floorInfo = serial.GetAllFloor();
                foreach (var item in floorInfo)
                {
                    serial.phy_list.Add(item.physicsfloor);
                    serial.show_list.Add(item.displayfloor);
                    serial.act_list.Add(item.actualfloor);
                }
                devState.interval = Convert.ToInt32(jsonConfigHelper["Interval"]) * 1000;
                devState.serial = serial;
                devState.logPrint = log;
                serial.devState = devState;
                serial.logPrint = log;
                log.isPrint = dev.printlog;
                serial.ttrAMA1_receive = dev.ttrAMA1_receive;
                serial.ttrAMA2_receive = dev.ttrAMA2_receive;
                //serial.ttrAMA3_receive = dev.ttrAMA3_receive;
                //serial.ttrAMA3_send = dev.ttrAMA3_send;
                serial.sendport = dev.sendport;
                devState.devinfo = dev;
                devState.reporttime = dev.intervalTime;
                serial.QueryMode();
                serial.deviceid = dev.liftid;
                serial.mainIP = dev.mainIP;
                serial.mainPort = dev.mainPort;
                serial.packet = dev.packet;
                serial.light = dev.lightmode;
                serial.authmode = dev.authmode;

                if (dev.interval == 0)
                {
                    serial.interval = 25;//默认间隔25ms
                }
                else
                {
                    serial.interval = dev.interval;
                }

                devState.HDConnect();
                serial.OpenttyS0SerialPort("ttyS0", 9600, 2, 8, 1);
                //serial.OpenttyS0SerialPort("COM8", 9600, 2, 8, 1);
                serial.QueryElevatorStatus();
            }
            else if (dev.authmode == 2)
            {
                List<FloorInfo> floorInfo = hdzh_serial.GetAllFloor();
                foreach (var item in floorInfo)
                {
                    hdzh_serial.phy_list.Add(item.physicsfloor);
                    hdzh_serial.show_list.Add(item.displayfloor);
                    hdzh_serial.act_list.Add(item.actualfloor);
                }

                hdzh_devState.interval = Convert.ToInt32(jsonConfigHelper["Interval"]) * 1000;
                hdzh_devState.serial = hdzh_serial;
                hdzh_devState.logPrint = log;
                hdzh_serial.devState = hdzh_devState;
                hdzh_serial.logPrint = log;
                log.isPrint = dev.printlog;
                hdzh_serial.ttrAMA1_receive = dev.ttrAMA1_receive;
                hdzh_serial.ttrAMA2_receive = dev.ttrAMA2_receive;
                hdzh_serial.sendport = dev.sendport;
                hdzh_devState.devinfo = dev;
                hdzh_devState.reporttime = dev.intervalTime;
                hdzh_serial.QueryMode();
                hdzh_serial.liftid = dev.liftid;
                hdzh_serial.mainIP = dev.mainIP;
                hdzh_serial.mainPort = dev.mainPort;
                hdzh_serial.packet = dev.packet;
                hdzh_serial.light = dev.lightmode;
                hdzh_serial.authmode = dev.authmode;
                hdzh_serial.GetCmd(dev.liftid, 1, 4);
                hdzh_serial.SlaveInterval = Convert.ToInt32(jsonConfigHelper["SlaveInterval"]);
                hdzh_serial.OpenS0SerialPort("ttyS0", 9600, 2, 8, 1);
                hdzh_serial.OpenS1SerialPort_2("ttyS1", 9600, 2, 8, 1);
                hdzh_serial.OpenFaceSerialPort("ttyUSB0", 9600, 2, 8, 1);
                hdzh_devState.HDConnect();
                hdzh_serial.CheckDevConnect();
                hdzh_serial.CheckS0ElevatorStatus();


                if (dev.enable == 1)
                {
                    if (dev.protocoltype.ToUpper() == "CLIENT")
                    {
                        hdzh_serial.ismaster = false;
                        hdzh_serial.ConnectServer(dev.mainIP, dev.mainPort);
                        //hdzh_serial.CheckMasterConnectStatus();
                    }
                    else
                    {
                        string ip = hdzh_devState.GetMIniLocalIP();
                        LogHelper.Log("主梯ip" + ip);
                        hdzh_serial.StartServer(ip, dev.mainPort);
                        hdzh_serial.ismaster = true;
                        hdzh_serial.CheckSlaveConnectStatus();
                    }
                    hdzh_serial.parallel = true;
                }

            }
            else if (dev.authmode == 3)
            {
                List<FloorInfo> floorInfo = hdzh_serial.GetAllFloor();
                foreach (var item in floorInfo)
                {
                    shgd_serial.phy_list.Add(item.physicsfloor);
                    shgd_serial.show_list.Add(item.displayfloor);
                    shgd_serial.act_list.Add(item.actualfloor);
                }

                FXMqttClient = new FXMqttClient();
                shgd_serial.clientBUS = new MqttClientBUS();
                shgd_serial.topic = FXMqttClient.SubscribeTopic;
                MqttDAL mqttDAL = new MqttDAL();
                MqttInfo mqttInfo = mqttDAL.GetMqttInfo();
                shgd_serial.device_id = mqttInfo.device_id;
                shgd_serial.number = mqttInfo.number;
                shgd_serial.ele_type = mqttInfo.ele_type;
                shgd_serial.liftid = dev.liftid;
                shgd_serial.server_ip = dev.serverIP;
                shgd_serial.server_port = dev.serverport;
                shgd_serial.topic_2 = string.Format("{0}/{1}/{2}/sys/property/up", mqttInfo.version, AppSettingsHelper.Configuration["ProductKey"], AppSettingsHelper.Configuration["SerialNumber"]);
                int DataSimulation = Convert.ToInt32(AppSettingsHelper.Configuration["DataSimulation"]);
                shgd_serial.DataSimulation = DataSimulation;
                shgd_serial.VirtualInterval = Convert.ToInt32(AppSettingsHelper.Configuration["VirtualInterval"]) * 1000;
                shgd_serial.mqttsend = Convert.ToInt32(AppSettingsHelper.Configuration["MqttSend"]);
                shgd_serial.mqttlog = Convert.ToInt32(AppSettingsHelper.Configuration["MqttPrint"]);
                shgd_serial.off_time = Convert.ToInt32(AppSettingsHelper.Configuration["OffTime"]) * 1000;
                Encry = Convert.ToInt32(AppSettingsHelper.Configuration["Encry"]);
                if (Encry == 1)
                {
                    try
                    {
                        string filepath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/PublicKey.xml";
                        if (File.Exists(filepath))
                        {
                            FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "wwwroot/PublicKey.xml", FileMode.Open, FileAccess.Read);
                            byte[] buffer = new byte[1024 * 1024 * 5];
                            int r = fileStream.Read(buffer, 0, buffer.Length);
                            publickey = Encoding.Default.GetString(buffer, 0, r);
                            fileStream.Close();
                            fileStream.Dispose();
                        }
                    }
                    catch
                    {

                    }
                }
                shgd_serial.Connect(dev.serverIP, dev.serverport);

                if (DataSimulation == 1)
                {
                    shgd_serial.dataSimulation();
                }
                else if (DataSimulation == 2)
                {
                    shgd_serial.YYLdataSimulation();
                }
                else
                {
                    if (mqttInfo.ele_type == 1)
                    {
                        int BaudRate = Convert.ToInt32(AppSettingsHelper.Configuration["BaudRate"]);
                        int Parity = Convert.ToInt32(AppSettingsHelper.Configuration["Parity"]);
                        int dataBits = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits"]);
                        int stopBits = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits"]);
                        shgd_serial.OpenS0SerialPort("ttyS0", BaudRate, Parity, dataBits, stopBits);
                        shgd_serial.QueryDTElevatorStatus();
                    }
                    else if (mqttInfo.ele_type == 2)
                    {
                        int BaudRate_2 = Convert.ToInt32(AppSettingsHelper.Configuration["BaudRate_2"]);
                        int Parity_2 = Convert.ToInt32(AppSettingsHelper.Configuration["Parity_2"]);
                        int DataBits_2 = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits_2"]);
                        int StopBits_2 = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits_2"]);
                        shgd_serial.OpenS1SerialPort("ttyS1", BaudRate_2, Parity_2, DataBits_2, StopBits_2);
                        shgd_serial.QueryElevatorStatus();
                    }
                }
            }
            else if (dev.authmode == 4)
            {
                pz_serial.logPrint = log;
                log.isPrint = dev.printlog;
                int BaudRate = Convert.ToInt32(AppSettingsHelper.Configuration["BaudRate"]);
                int Parity = Convert.ToInt32(AppSettingsHelper.Configuration["Parity"]);
                int dataBits = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits"]);
                int stopBits = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits"]);
                pz_serial.OpenS0SerialPort("ttyS0", BaudRate, Parity, dataBits, stopBits);
                pz_serial.liftid = Convert.ToInt32(AppSettingsHelper.Configuration["Liftid"]);
                pz_serial.add_start = Convert.ToInt32(AppSettingsHelper.Configuration["StorageStart"]);
                pz_serial.add_count = Convert.ToInt32(AppSettingsHelper.Configuration["StorageCount"]);
                pz_serial.PZInterval = Convert.ToInt32(AppSettingsHelper.Configuration["PZInterval"]);
                pz_serial.numberno = AppSettingsHelper.Configuration["SerialNumber"];
                pz_serial.remark = AppSettingsHelper.Configuration["Remark"];
                pz_serial.QueryElevatorStatus();
                PZMqttClient = new PZMqttClient();
                pz_serial.clientBUS = new PZMqttClientBUS();
                pz_serial.topic = PZMqttClient.SubscribeTopic;
            }
            else if (dev.authmode == 5)
            {
                dy_serial.OpenS0SerialPort("ttyS0", 9600, 0, 8, 1);
                dy_serial.OpenS1SerialPort("ttyS1", 9600, 0, 8, 1);
                dy_serial.QueryElevatorStatus();
            }
            else if (dev.authmode == 6)
            {
                data_serial.Start(dev.mainPort);
            }
            else if (dev.authmode == 7)
            {
                cems_serial.OutboundInterval = Convert.ToInt32(AppSettingsHelper.Configuration["OutboundInterval"]);
                cems_serial.HeartCheck= Convert.ToInt32(AppSettingsHelper.Configuration["HeartCheck"]);
                //List<FloorInfo> floorInfo = serial.GetAllFloor();
                //foreach (var item in floorInfo)
                //{
                //    cems_serial.phy_list.Add(item.physicsfloor);
                //    cems_serial.show_list.Add(item.displayfloor);
                //    cems_serial.act_list.Add(item.actualfloor);
                //}

                int BaudRate = Convert.ToInt32(AppSettingsHelper.Configuration["BaudRate"]);
                int Parity = Convert.ToInt32(AppSettingsHelper.Configuration["Parity"]);
                int dataBits = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits"]);
                int stopBits = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits"]);
                int face_port= Convert.ToInt32(AppSettingsHelper.Configuration["FacePort"]);
                string portname = AppSettingsHelper.Configuration["PortName"];
                //可视对讲
                cems_serial.OpenS0SerialPort(portname, BaudRate, Parity, dataBits, stopBits);
                //人脸识别
                cems_serial.Face_Start(face_port);
                cems_serial.CmdListSend();

            }
        }



        public string GetIP()
        {
            try
            {
                //本地计算机网络连接信息
                IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
                //获取本机所有网络连接
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

                if (nics == null || nics.Length < 1)
                {
                    return "";
                }
                foreach (NetworkInterface adapter in nics)
                {
                    var adapterName = adapter.Name;
                    if (adapterName == "eth0")
                    {
                        return adapter.GetIPProperties().UnicastAddresses[0].Address.ToString();
                    }
                }
                return "";

            }
            catch
            {
                return "";
            }
        }
    }
}
